package com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.service.impl;

import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.entity.InvestigationTeam;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.repository.InvestigationGroupRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.entity.InvestigationTask;
import com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.repository.InvTaskManageRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.service.InvTaskManageService;
import com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.vo.InvestigationTaskVo;
import com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.vo.UpdateVo;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.entity.SurTaskManage;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.repository.SurTaskManageRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.vo.UpdateVO;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.JcStrongCatalog;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.repository.EarEveManageRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.util.*;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import com.css.fxfzxczh.zcpt.sys.service.impl.SUserServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Author:
 * @CreateTime: 2023/10/24 16:28
 * @Description:
 */
@Service
public class InvTaskManageServiceImpl implements InvTaskManageService {

    @Resource
    InvTaskManageRepository invTaskManageRepository;
    @Resource
    SurTaskManageRepository surTaskManageRepository;
    @Resource
    EarEveManageRepository earEveManageRepository;

    @Resource
    private InvestigationGroupRepository investigationGroupRepository;
    
    @Resource
    SUserService sUserService;

    @Resource
    EarEveManageService earEveManageService;

    @Resource
    private RedisLockUtil redisLockUtil;

    /**
     * 数据源
     * 10.19.41.111
     */
    @Value("${spring.datasource.url}")
    private String url = "";
    @Value("${spring.datasource.username}")
    private String name = "";
    @Value("${spring.datasource.password}")
    private String pwd = "";

    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, String xsemId) {
        Map<String, Object> page = invTaskManageRepository.getPage(curPage, pageSize,xsemId);
        return page;
    }

    @Override
    public List<InvestigationTaskVo> getTaskList(String xsemId,String taskType) {
        return invTaskManageRepository.getTaskList(xsemId,taskType);
    }

    @Override
    public void save(InvestigationTask investigationTask) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        investigationTask.setXitmId(UUIDGenerator.getUUID());
        investigationTask.setDelFlag(YNEnum.N.toString());
        investigationTask.setTaskStatus("0");
        investigationTask.setXsemId(currentEvent.getXsemId());
        investigationTask.setXsemCode(currentEvent.getEventCode());
        invTaskManageRepository.save(investigationTask);
    }

    @Override
    public void update(InvestigationTask investigationTask) {
        investigationTask.setUpdateTime(new Date());
        investigationTask.setUpdateUser(PlatformSessionContext.getUserID());
        invTaskManageRepository.update(investigationTask);
    }

    @Override
    public InvestigationTask findById(String id) {
        return invTaskManageRepository.findById(id);
    }

    @Override
    public void deleteById(List<String> id) {
        invTaskManageRepository.deleteById(id);
    }

    @Override
    public Map<String, Object> getCode() {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        String eventCode=currentEvent.getEventCode();
        Map<String, Object> map=new HashMap<>();
        StringBuilder taskCode = new StringBuilder(eventCode+"DCRW");



        map.put("taskCode",getCodeFun(taskCode));
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        map.put("createUserName", sUser.getUserName());
        map.put("createUser", sUser.getUserId());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("createTime", dateFormat.format(new Date()));
        return map;
    }

    @Override
    public List<List<String>> getAdministrativeDivisionByGeomText(String geomText) {
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(geomText)) {
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:省|市|区县|乡镇
                List<String> codeList = new ArrayList<String>();//行政区划编码列表:省|市|区县
                //查询行政区划
                String sql = "select c.name as province,c.code as code1,b.name as city,b.code as code2,a.name as county,a.code as code3 from district_boundary_county a " +
                        "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                        "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000')," +
                        "(select ST_GeometryFromText('"+geomText+"',4490) as geom) t " +
                        "where ST_Intersects(a.geom,t.geom) " +
                        "and ST_Touches(a.geom,t.geom)!='t' " +
                        "order by a.code,b.code,c.code;";
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    String province = rs.getString("province");//行政区划名称--省
                    String city = rs.getString("city");//行政区划名称--市
                    String county = rs.getString("county");//行政区划名称--区县
                    if (!PlatformObjectUtils.isEmpty(province) && !PlatformObjectUtils.isEmpty(city) && !PlatformObjectUtils.isEmpty(county)){
                        String name = province + "-" + city + "-" + county;
                        nameList.add(name);//行政区划名称--省-市-区县
                        String code1 = rs.getString("code1");//行政区划编码--省
                        String code2 = rs.getString("code2");//行政区划编码--市
                        String code3 = rs.getString("code3");//行政区划编码--区县
                        String code = code1 + "-" + code2 + "-" + code3;
                        codeList.add(code);
                    }
                }
                if(nameList.size()>0){
                    resultList.add(nameList);//行政区划名称列表
                    resultList.add(codeList);//行政区划编码列表
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }

    @Override
    public void accTotheGroupSave(List<InvestigationTask> list) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        String eventCode = currentEvent.getEventCode();
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);

        for(InvestigationTask item:list){
            item.setXitmId(UUIDGenerator.getUUID());
            item.setDelFlag(YNEnum.N.toString());
            item.setTaskStatus("0");
            item.setCreateUser(userId);
            item.setCreateUserName(sUser.getUserName());
            StringBuilder taskCode = new StringBuilder(eventCode+"DCRW");
            item.setTaskCode(getCodeFun(taskCode));
            item.setCreateTime(new Date());
            invTaskManageRepository.save(item);
        }
        //invTaskManageRepository.batchSave(list);
    }

    @Override
    public List<InvestigationTaskVo> getAppTaskList(String xsemId, String userId) {
        List<InvestigationTaskVo> invTaskList = this.getTaskList(xsemId,"");
        for(InvestigationTaskVo invTask:invTaskList){
            if(PlatformObjectUtils.isNotEmpty(invTask.getGroupId())){
                invTask.setWheUndTask(whetherUndertakeTask(invTask.getGroupId(),userId));
            }else{
                invTask.setWheUndTask("0");
            }
        }
        //评估子区任务列表
        List<SurTaskManage> surTaskList = surTaskManageRepository.getTaskListByXsemId(xsemId);
        for(SurTaskManage surTask:surTaskList){
            InvestigationTaskVo invTask=new InvestigationTaskVo();
            BeanUtils.copyProperties(surTask, invTask);
            invTask.setXitmId(surTask.getXstmId());
            invTask.setTaskName(surTask.getEvaluationSubareaName());
            invTask.setTaskCode(surTask.getEvaluationSubareaCode());
            invTask.setTaskRange(surTask.getEvaluationSubareaRange());
            //代表子区任务
            invTask.setTaskType("2");
            if(PlatformObjectUtils.isNotEmpty(invTask.getGroupId())){
                invTask.setWheUndTask(whetherUndertakeTask(invTask.getGroupId(),userId));
            }else{
                invTask.setWheUndTask("0");
            }
            invTaskList.add(invTask);
        }



        // 使用Comparator比较器来排序
        Comparator<InvestigationTaskVo> comparator = Comparator.comparing(InvestigationTaskVo::getCreateTime);
        // 使用reversed()方法使排序降序
        comparator = comparator.reversed();
        // 调用sort方法对列表进行排序
        Collections.sort(invTaskList, comparator);

        return invTaskList;
    }

    @Override
    public Map<String, Object> getAppPageTaskList(String xsemId,String userId,int curPage,int pageSize) {
        //userId="705197d3066045f3a4740343e3cd964d";
        //调查任务列表
        List<InvestigationTaskVo> invTaskList = this.getTaskList(xsemId,"");
        for(InvestigationTaskVo invTask:invTaskList){
            if(PlatformObjectUtils.isNotEmpty(invTask.getGroupId())){
                invTask.setWheUndTask(whetherUndertakeTask(invTask.getGroupId(),userId));
            }else{
                invTask.setWheUndTask("0");
            }
        }
        //评估子区任务列表
        List<SurTaskManage> surTaskList = surTaskManageRepository.getTaskListByXsemId(xsemId);
        for(SurTaskManage surTask:surTaskList){
            InvestigationTaskVo invTask=new InvestigationTaskVo();
            BeanUtils.copyProperties(surTask, invTask);
            invTask.setXitmId(surTask.getXstmId());
            invTask.setTaskName(surTask.getEvaluationSubareaName());
            invTask.setTaskCode(surTask.getEvaluationSubareaCode());
            invTask.setTaskRange(surTask.getEvaluationSubareaRange());
            //代表子区任务
            invTask.setTaskType("2");
            if(PlatformObjectUtils.isNotEmpty(invTask.getGroupId())){
                invTask.setWheUndTask(whetherUndertakeTask(invTask.getGroupId(),userId));
            }else{
                invTask.setWheUndTask("0");
            }
            invTaskList.add(invTask);
        }


        //手动分页
        List<InvestigationTaskVo> pageList = HandMovementPageUtil.startPage(invTaskList, curPage, pageSize);
        // 使用Comparator比较器来排序
        Comparator<InvestigationTaskVo> comparator = Comparator.comparing(InvestigationTaskVo::getCreateTime);
        // 使用reversed()方法使排序降序
        comparator = comparator.reversed();
        // 调用sort方法对列表进行排序
        Collections.sort(pageList, comparator);
        Map<String, Object> map=new HashMap<>();
        map.put("total", pageList.size());
        map.put("rows", pageList);
        return map;
    }

    @Override
    public void updateTaskStatu(UpdateVo updateVo) {
        InvestigationTask investigationTask = invTaskManageRepository.findById(updateVo.getXitmId());
        String groupId = investigationTask.getGroupId();
        if(PlatformObjectUtils.isNotEmpty(groupId)){
            InvestigationTeam group = investigationGroupRepository.findById(groupId);
            if(updateVo.getUserId().equals(group.getLeaderId())){
                invTaskManageRepository.updateTaskStatu(updateVo.getXitmId(),updateVo.getTaskStatus());
            }else{
                throw new RuntimeException("当前登录账号不是该任务所承担小组的组长账号");
            }
        }else{
            throw new RuntimeException("该任务尚未分配小组，无法开始任务");
        }





        /*EarEveManage currentEvent = earEveManageRepository.getCurrentEvent(updateVo.getUserId());
        List<InvestigationTeam> list=investigationGroupRepository.findByLeaderId(updateVo.getUserId(),currentEvent.getXsemId());
        if(list.size()>0){
            invTaskManageRepository.updateTaskStatu(updateVo.getXitmId(),updateVo.getTaskStatus());
        }else{
            throw new RuntimeException("当前登录账号不是组长账号");
        }*/
    }

    @Override
    public void deleteByXsemId(String xsemId) {
        invTaskManageRepository.deleteByXsemId(xsemId);
    }

    //判断是否承担该任务
    private String whetherUndertakeTask(String groupId,String userId){
        InvestigationTeam group = investigationGroupRepository.findById(groupId);
        List<String> teamMemberId=investigationGroupRepository.getTeamMemberId(group.getXitId());
        //teamMemberId.add(group.getLeaderId());
        if(group.getLeaderId().equals(userId)){
            return "2";
        }if(teamMemberId.contains(userId)){
            return "1";
        }else{
            return "0";
        }
    }

    /**
     * 获取数据库连接
     * SQL语句
     */
    private Connection getConnection() throws Exception {
        //Class.forName("com.mysql.cj.jdbc.Driver");
        Class.forName("org.postgresql.Driver");
        return DriverManager.getConnection(url, name, pwd);
    }

    private String getCodeFun(StringBuilder code) {

        DecimalFormat decimalFormat=new DecimalFormat("000");
        String num="";
        String maxCode="";

        String requestId = UUIDGenerator.getUUID();
        Boolean isLocked = redisLockUtil.lock("redis_eventCode_lock_serialNum", requestId, 3L);
        if (isLocked) {

            maxCode = invTaskManageRepository.getMaxTaskCode(code.toString());


            if (PlatformObjectUtils.isEmpty(maxCode)) {
                int i = 1;
                num = decimalFormat.format(i);
            } else {
                String substring = maxCode.substring(maxCode.length() - 3);
                num = decimalFormat.format(Integer.parseInt(substring) + 1);
            }
            redisLockUtil.releaseLock("redis_distributed_lock_serialNum", requestId);
        }else {
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return code.append(num).toString();
    }
}
